﻿using IterationLife.System.Models;
using IterationLife.System.Tools;
using Util;

namespace IterationLife.System.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class SignInManager : ISignInManager
    {
        private readonly IUserManager _userManager;
        public SignInManager(IUserManager userManager)
        {
            _userManager = userManager;
        }

        public SignInResult PasswordSignIn(string account, string password)
        {
            SignInResult result = new SignInResult();
            var user = _userManager.FindUserByAccount(account);
            if (user == null)
                return result;

            result.Succeeded=_userManager.VerifyPassword(user, password);
            result.IsLockedOut = user.IsLock;
            result.IsNotAllowed = !user.Enabled;
            result.Token = AuthenticationTokenHelper.GenerateToken(user);
            result.UserId = user.Id.SafeString();
            return result;
        }

        public SignInResult ExternalLoginSignIn(string loginProvider, string externalId)
        {
            SignInResult result = new SignInResult();
            var user = _userManager.FindUserByExternalLogin(loginProvider, externalId);
            if (user == null)
                return result;

            result.Succeeded = true;
            result.IsLockedOut = user.IsLock;
            result.IsNotAllowed = !user.Enabled;
            result.Token = AuthenticationTokenHelper.GenerateToken(user);
            result.UserId = user.Id.SafeString();
            return result;
        }

        public SignInResult SignIn(User user)
        {
            SignInResult result = new SignInResult();
            user = _userManager.FindUserByAccount(user.UserName);
            if (user == null)
                return result;

            result.Succeeded = true;
            result.IsLockedOut = user.IsLock;
            result.IsNotAllowed = !user.Enabled;
            result.Token = AuthenticationTokenHelper.GenerateToken(user);
            result.UserId = user.Id.SafeString();
            return result;
        }
    }
}
